#version 150

struct Light
{
	vec3 pos;
	float power;
	vec3 color;
};

const int MAX_LIGHTS = 4;

in vec2 Texcoord;
in vec3 VertexPos_World;
in float Depth;
in vec3 EyeDir_Tan;
in vec3 LightDir_Tan[MAX_LIGHTS];

out vec4 outColor;
out vec4 outDepth;

uniform int lightCount;
uniform Light lights[MAX_LIGHTS];
uniform vec3 ambientColor;
uniform vec3 diffuseColor;
uniform vec3 specularColor;
uniform float specularCoeff;
uniform float alpha;
uniform sampler2D tex0;
uniform sampler2D tex0normal;

void main() 
{
	outColor = vec4(0.0);
	
	vec3 materialDiffuseColor = texture(tex0, Texcoord).xyz * diffuseColor;
	vec3 materialAmbientColor = ambientColor * materialDiffuseColor;
	vec3 materialSpecularColor = specularColor;
	
	for (int i = 0; i < lightCount; ++i)
	{	
		float lightDistance = length(lights[i].pos - VertexPos_World);
		
		vec3 n = normalize(texture(tex0normal, Texcoord).rgb * 2.0 - 1.0);
		vec3 l = normalize(LightDir_Tan[i]);
		float diff = clamp(dot(n,l), 0, 1);
				
		vec3 R = reflect(-l,n);
		vec3 E = normalize(EyeDir_Tan);
		float spec = clamp(dot(E,R), 0, 1);		
		
		outColor.rgb += 
				materialAmbientColor +
				materialDiffuseColor * lights[i].color * lights[i].power * diff / (lightDistance * lightDistance) +
				materialSpecularColor * lights[i].color * lights[i].power * pow(spec, specularCoeff) / (lightDistance * lightDistance);
	}
	
	outColor.a = alpha;	
	outDepth = vec4(Depth, Depth, Depth, 1.0);
}